package com.qf.user.manager.api;

import com.qf.common.bean.R;
import com.qf.common.model.QfUser;
import com.qf.common.utils.JwtUtil;
import com.qf.user.manager.bean.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.UUID;

/**
 * 管理员授权认证
 * @author 千锋健哥
 */
@RestController
@RequestMapping("/user/auth")
public class UserAuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 登录认证
     * @return
     */
    @PostMapping("/doLogin")
    public R<String> login(@RequestBody(required = false) QfUser qfUser) {
        //1. 判断如果传入对象为空, 给出提示
        if (qfUser == null) {
            return R.fail("用户名, 密码不能为空!");
        }
        //2. 判断用户名密码是否为空, 提出提示
        if (StringUtils.isEmpty(qfUser.getUserName())
                || StringUtils.isEmpty(qfUser.getPassword())) {
            return R.fail("用户名, 密码不能为空!");
        }

        //3. 调用SpringSecurity的认证方法, 将用户名, 密码交给框架并触发UserDetailService实现类
        Authentication authenticate = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(qfUser.getUserName(), qfUser.getPassword()));
        if (Objects.isNull(authenticate)) {
            return R.fail("认证失败, 用户名密码错误!");
        }
        //4. 获取当前登录用户的用户名
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userName = loginUser.getQfUser().getUserName();

        //5. 生成jwt返回
        String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), userName, null);
        return R.ok(jwt);
    }
}
